<?php

namespace App\Http\Controllers\Admin;

use App\Models\Activity;
use App\Models\AlbumImage;
use App\Models\ParticipantActivity;
use App\Models\Survey;
use App\Models\User;
use App\Org\Developer\Helper;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 用户列表首页
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('admin.user.index');
    }

    /**
     * 异步获取列表数据
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function lists(Request $request)
    {
        if ($request->ajax()) {
            $offset = intval($request->get('start'));
            $paginate = User::select(['id', 'username', 'created_at'])->orderBy('id', 'desc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);
            
            $data = [];
            foreach ($paginate as $item) {
                $data[] = [
                    $item->id,
                    $item->username,
                    $item->created_at->toDateTimeString(),// 这个 created_at 是特例，可以使用 toDateTimeString() 方法。而 start_time、end_time 则不行。
                    // '<a type="button" class="btn btn-primary btn-xs">查看</a>',
                    '<a href="'. url('admin/user/activitySurveyList/' . $item->id) .'" type="button" class="btn btn-primary btn-xs"><i class="fa fa-eye"></i> 查看</a> <a type="button" class="btn btn-danger btn-xs btn-remove" data-id="'. $item->id .'"><i class="fa fa-remove"></i> 删除</a>',
                    // '<a href="javascript:void(0);" type="button" class="btn btn-primary btn-xs">查看</a>',
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return response()->json(['code' => 4000]);
        }

        try {
            // 检查该用户是否存在
            $updateModel = User::select(['id', 'name', 'username'])->find($id);
            if (!(isset($updateModel) && $updateModel->name)) {
                return response()->json(['code' => 4001]);
            }

            $result = $updateModel->delete();
            if ($result) {
                return response()->json(['code' => 200]);
            }
            return response()->json(['code' => 4002]);
        } catch (\Exception $e) {
            return response()->json(['code' => 5555]);
        }
    }

    /**
     * 查看用户创建的活动、调查等情况
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function activitySurveyList($id)
    {
        return view('admin.user.user-activity-survey', ['id' => $id]);
    }

    /**
     * 异步获取列表数据（根据 user_id 获取 activity 详情）
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function activityList(Request $request, $id)
    {
        if ($request->ajax()) {
            $offset = intval($request->get('start'));
            $paginate = Activity::select(['id', 'type', 'title', 'bg_image_url', 'counts', 'start_time', 'end_time', 'created_at'])
                ->where(['user_id' => $id])->orderBy('id', 'desc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);

            $data = [];
            foreach ($paginate as $item) {
                $data[] = [
                    $item->id,
                    $item->type,
                    $item->title,
                    $item->bg_image_url,
                    $item->counts,
                    $item->start_time,
                    $item->end_time,
                    $item->created_at->toDateTimeString(),
                    '<a type="button" data-main-type="activity" data-type="'. $item->type .'" data-id="'. $item->id .'" class="btn btn-primary btn-xs btn-view"><i class="fa fa-eye"></i> 查看</a>',
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * 某一个活动
     */
    public function activityDetail(Request $request, $id)
    {
        $model = Activity::find($id);
        if ($model->type == 'screen') {
            $models = AlbumImage::select(['album_images.album_id', 'album_images.image_url', 'albums.album_type_id'])

                ->join('albums', function($join) {
                    $join->on('albums.id', '=', 'album_images.album_id');
                })

                ->where('album_images.album_id', function($query) use ($id) {
                    $query->select('id')->from('albums')->where(['activity_id' => $id]);
                })

                ->get();

            return response()->json(['errorCode' => 0, 'errorMessage' => '', 'result' => $models]);
        } else if ($model->type == 'game') {

            //SELECT p.username,p.nickname,pa.score FROM thearte_participant_activities AS pa LEFT JOIN thearte_participants p ON p.id = pa.participant_id
            // ORDER BY pa.score DESC,pa.id ASC

            $models = ParticipantActivity::select(['participants.nickname', 'participant_activities.score'])

                ->join('participants', function($join) {
                    $join->on('participants.id', '=', 'participant_activities.participant_id');
                })

                ->where(['participant_activities.activity_id' => $id])

                ->get();

            return response()->json(['errorCode' => 0, 'errorMessage' => '', 'result' => $models]);
        }

        return response()->json(['errorCode' => 5555, 'errorMessage' => '没有数据.', 'id' => $id, 'type' => $model->type]);
    }

    /**
     * 异步获取列表数据（根据 user_id 获取 survey 详情）
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function surveyList(Request $request, $id)
    {
        if ($request->ajax()) {
            $offset = intval($request->get('start'));
            $paginate = Survey::select(['id', 'title', 'illustration', 'type', 'counts', 'start_time', 'end_time', 'created_at'])
                ->where(['user_id' => $id])->orderBy('id', 'desc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);

            $data = [];
            foreach ($paginate as $item) {
                $data[] = [
                    $item->id,
                    $item->title,
                    $item->illustration,
                    $item->type == 'vote' ? '投票' : '问卷',
                    $item->counts,
                    $item->start_time,
                    $item->end_time,
                    $item->created_at->toDateTimeString(),
                    '<a type="button" data-main-type="survey" data-type="'. $item->type .'" data-id="'. $item->id .'" class="btn btn-primary btn-xs btn-view"><i class="fa fa-eye"></i> 查看</a>',
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * 某一个调查
     */
    public function surveyDetail(Request $request, $id)
    {

        $model = Survey::find($id);
        if ($model->type == 'vote') {
            $sql = "SELECT vt.illustration AS title,t.counts FROM 
            (SELECT title_id,COUNT(title_id) AS counts FROM thearte_vote_results WHERE survey_id={$id} GROUP BY title_id) AS t 
            LEFT JOIN thearte_vote_titles AS vt ON vt.id=t.title_id";

            $models = \Illuminate\Support\Facades\DB::select($sql);
            return response()->json(['errorCode' => 0, 'errorMessage' => '', 'result' => $models]);
        } else if ($model->type == 'questionnaire') {
            $sql = "SELECT o.name AS title,t.counts FROM 
            (SELECT option_id,COUNT(option_id) AS counts FROM thearte_questionnaire_results WHERE title_id IN 
            (SELECT id FROM thearte_questionnaire_titles WHERE survey_id={$id}) GROUP BY option_id) AS t 
            LEFT JOIN thearte_questionnaire_options AS o ON o.id=t.option_id";

            $models = \Illuminate\Support\Facades\DB::select($sql);
            return response()->json(['errorCode' => 0, 'errorMessage' => '', 'result' => $models]);
        }
        return response()->json(['errorCode' => 5555, 'errorMessage' => '没有数据.']);
    }
}
